package com.zretc.answer.service;

import com.zretc.answer.dao.AnswerMapper;
import com.zretc.api.pojo.Answer;
import com.zretc.api.pojo.InternalReferral;
import com.zretc.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class AnswerService {
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private RedisService redisService;
    public boolean giveAnswer(Answer answer)
    {
        return answerMapper.addSingleRecord(answer)==1;
    }
    public boolean deleteAnswerByUser(Integer id,Integer fromId)
    {
        if(fromId==answerMapper.getFromIdOfAnswerById(id))
        {
            return answerMapper.deleteSingleRecord(id)==1;
        }
        return false;
    }
    public boolean deleteAnswerByIRPublisher(Integer id,Integer iRPublisherId )
    {
        if(iRPublisherId==answerMapper.getIRPublisherIdOfAnswerById(id))
        {
            return answerMapper.deleteSingleRecord(id)==1;
        }
        return false;
    }
    public List<Answer> queryAnswersByAmountByQuestionId(Integer index,Integer pageNum,Integer questionId)
    {
        String redisKey="Q:"+questionId+"answerList:"+index+","+pageNum;
        List<Answer> result=redisService.getCacheList(redisKey);
        if (CollectionUtils.isEmpty(result))
        {
            result=answerMapper.getAnswersByAmountByQuestionId(index, pageNum, questionId);
            if(CollectionUtils.isEmpty(result))return null;
            redisService.setCacheList(redisKey,result);
        }
        redisService.expire(redisKey,5);
        return result;
    }

}
